/**
 * Wihidum - Efficient Broker Hierarchy for Publish Subscribe Middleware
 *
 * License      :   Apache License 2.0
 * Home Page    :   http://code.google.com/p/wihidum/
 * Mailing List :   wihidum@googlegroups.com
 */

package lk.mrt.cse.wihidum.subscriber.processor;

import lk.mrt.cse.wihidum.util.*;
import org.apache.axiom.om.*;
import org.apache.axis2.*;
import org.apache.axis2.addressing.*;
import org.apache.axis2.client.*;
import org.apache.log4j.*;

import javax.xml.namespace.*;

/**
 * Process get publications messages
 */
public class GetPublicationsProcessor
        implements Processor
{
    private static final Logger logger = Logger.getLogger (GetPublicationsProcessor.class);

    /**
     * @see lk.mrt.cse.wihidum.subscriber.processor.Processor#processMessage(org.apache.axiom.om.OMElement)
     */
    public OMElement processMessage (OMElement requestElement)
    {
        try
        {
            logger.info ("Processing get publications message");

            OMElement subscriptionIDElement = requestElement.getFirstChildWithName (new QName ("subscriptionID"));
            OMElement listenerAddressElement = requestElement.getFirstChildWithName (new QName ("listenerAddress"));

            ServiceClient serviceClient = new ServiceClient ();
            Options options = new Options ();
            options.setTo (new EndpointReference (listenerAddressElement.getText ()));
            options.setAction ("getPublications");
            serviceClient.setOptions (options);

            OMFactory factory = OMAbstractFactory.getOMFactory ();

            OMElement messageElement = factory.createOMElement ("GetPublicationsRequest", null);

            OMElement subscriptionHeader = factory.createOMElement ("Header", null);
            OMElement actionElement = factory.createOMElement ("Action", null);
            actionElement.setText (WihidumConstants.Operations.GET_PUBLICATIONS);
            subscriptionHeader.addChild (actionElement);
            messageElement.addChild (subscriptionHeader);

            messageElement.addChild (subscriptionIDElement);

            return serviceClient.sendReceive (messageElement);
        }
        catch (AxisFault ex)
        {
            logger.error ("Error in processing get publications message", ex);
            return null;
        }
        catch (OMException ex)
        {
            logger.error ("Error in processing get publications message", ex);
            return null;
        }
    }

}